import React from 'react';
import { Carousel } from 'antd-mobile';
import * as utils from '../../../../components/utils/utils';
import './banner.css';

class Banner extends React.Component {
    constructor (props) {
        super(props);

        this.state = {
            list: []
        };

        this.storage = {
        };
    }

    static getDerivedStateFromProps (props, state) {
        return {
            list: props.list
        };
    }

    componentDidMount () {
    }

    handleBannerItemClick (url) {
        const webRegexp = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
        const isWeb = webRegexp.test(url);

        utils.navigate(url, isWeb);
    }

    renderBanner () {
        const length = this.state.list.length;
        if (length === 0) {
            return null;
        }
        if (length === 1) {
            return (
                <div className="banner">
                    <div className="item" onClick={() => { this.handleBannerItemClick(this.state.list[0].target); }}>
                        <img src={this.state.list[0].pic_url} />
                    </div>
                </div>
            );
        }
        if (length > 1) {
            return (
                <div className="banner">
                    <Carousel dots={false} autoplay={true} infinite={true} autoplayInterval={3000}>
                        {
                            this.state.list.map((item, index) => {
                                return (
                                    <div className="item" key={index} onClick={() => { this.handleBannerItemClick(item.target); }}>
                                        <img src={item.pic_url} />
                                    </div>
                                );
                            })
                        }
                    </Carousel>
                </div>
            );
        }
    }

    render () {
        return this.renderBanner();
    }
}
export default Banner;
